package com.example.controller;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.example.common.AutoLog;
import com.example.common.CaptureConfig;
import com.example.common.JwtInterceptor;
import com.example.common.Result;
import com.example.entity.Params;
import com.example.entity.Users;
import com.example.repository.UserDeviceMapper;
import com.example.service.UsersService;
import com.github.pagehelper.PageInfo;
import com.wf.captcha.utils.CaptchaUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.stream.Collectors;

@ResponseBody
@RestController
@CrossOrigin
@RequestMapping("/Users")
public class UsersController {

    private static final Logger log = LoggerFactory.getLogger(JwtInterceptor.class);

    @Resource
    private UsersService usersService;

    @Resource
    private UserDeviceMapper userDeviceMapper;

    /***
     *users
     */

    //新增和编辑共用一个请求路径，首先根据userId查询数据库
    //若数据库为空，则进行新增操作，否则进行修改操作
   @PostMapping("/saveUser")
   @AutoLog("修改用户信息")
    public Result saveUser(@RequestBody Users users){
       log.info("后端接收到的数据：" + String.valueOf(users));
       log.info("该用户可查看设备的deviceId：" + Arrays.toString(users.getDeviceIds()));
       //对users表进行更新
       if(users.getUserId() == null){
           usersService.addUser(users);
       }else{
            usersService.updateUser(users);
       }
       //对user_device表进行更新
       // 确保 userId 不为空，并且 deviceIds 不是 null
       if (users.getUserId() != null && users.getDeviceIds() != null) {
           usersService.updateUserDevices(users.getUserId(), Arrays.asList(users.getDeviceIds()));
       }
       return Result.success();
   }

    @DeleteMapping("/deleteUser/{userId}")
    @AutoLog("删除用户信息")
    public Result deleteUserById(@PathVariable long userId){
        usersService.deleteUser(userId);
        return Result.success();
    }

    @GetMapping("/findBySearchOfUsers")
    public Result findBySearchOfUsers(Params params){
       log.info("拦截器已放行，正式调用接口内部，查询管理员信息");
       log.info("后端接收到findBySearchOfUsers请求的参数：" + params);
        PageInfo<Users> search = usersService.findBySearchOfUsers(params);
        log.info("(根据后端接收的参数)调用findBySearchOfUsers方法后，从数据库查出的结果：" + search);
        return Result.success(search);
    }

    @GetMapping("/findDeviceIdsByUserId/{userId}" )
    public Result findDeviceIdsByUserId(@PathVariable Long userId){
        List<String> existDeviceIds = userDeviceMapper.selectDeviceIdsByUserId(userId);
        log.info("用户"+userId+"此时可查看设备都有+"+existDeviceIds);
        return Result.success(existDeviceIds);
    }

    @PostMapping("/login")
    @AutoLog("用户登录")
    public Result login(@RequestBody Users users, @RequestParam String key, HttpServletRequest request){
       log.info("登录的用户是："+String.valueOf(users));
       //判断验证码是否正确
        if(!users.getVerCode().toLowerCase().equals(CaptureConfig.CAPTURE_MAP.get(key))){
            //不相等，说明验证失败
            CaptchaUtil.clear(request);
            return Result.error("验证码验证失败！");
        }
        Users loginUser = usersService.login(users);
        CaptureConfig.CAPTURE_MAP.remove(key);
        return Result.success(loginUser);
    }

    @PutMapping("/deleteBatch")
    @AutoLog("删除用户信息")
    public Result deleteBatch(@RequestBody List<Users> list){
       usersService.deleteBatch(list);
       return Result.success();
    }

    @GetMapping("/echarts/bar")
    public Result bar(){
       List<Users> list = usersService.findAll();
        Map<String, Long> collect = list.stream()
                .filter(x -> ObjectUtil.isNotEmpty(x.getIdentity()))
                .collect(Collectors.groupingBy(Users::getIdentity,Collectors.counting()));
        List<String> xAxis = new ArrayList<>();
        List<Long> yAxis = new ArrayList<>();
        if(CollectionUtil.isNotEmpty(collect)){
            for (String key : collect.keySet()) {
                xAxis.add(key);
                yAxis.add(collect.get(key));
            }
        }
        Map<String, Object> map = new HashMap<>();
        map.put("xAxis", xAxis);
        map.put("yAxis", yAxis);

       return Result.success(map);
    }
}
